package com.scs.application.core.utils;

import com.scs.application.core.consts.Const;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * txt格式文件读写
 */
@Slf4j
public class FileUtils extends org.apache.commons.io.FileUtils {

    public static void main(String args[]) {
        // writeTxtFile(Const.MENU_FILE,"{a:'dddd'}");
        // System.out.println(readFile(Const.MENU_FILE));
    }

    /**
     * 读入TXT文件
     */
    public static String readFile(String path) {
        // 绝对路径或相对路径都可以
        StringBuilder sb = new StringBuilder();
        try (FileReader reader = new FileReader(path);
             BufferedReader br = new BufferedReader(reader);) {

            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    public static String readFileStore(String relativePath) {
        if (relativePath.startsWith("\\\\")) {
            relativePath = relativePath.replaceFirst("\\\\", "");
        } else if (relativePath.startsWith("/")) {
            relativePath = relativePath.replaceFirst("/", "");
        }
        String path = "";
        String protocol = Const.class.getClassLoader().getResource("").getProtocol();
        BufferedReader in = null;
        try {
            if (protocol.startsWith("jar")) {
                path = "/static/file-store/" + relativePath;
                InputStream resourceAsStream = FileUtils.class.getClassLoader().getResourceAsStream(path);
                in = new BufferedReader(new InputStreamReader(resourceAsStream, "UTF-8"));

            } else {
                path = System.getProperty("user.dir") + "/src/main/resources/static/file-store/" + relativePath;
                in = new BufferedReader(new FileReader(path));
            }

            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            String input = buffer.toString();
            return input;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("FileUtils.readFileStore.e", e);
            log.error("FileUtils.readFileStore.relativePath={}", relativePath);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static List<String> readFileLinesStore(String relativePath) {
        List<String> strLine = new ArrayList<String>();
        if (relativePath.startsWith("\\\\")) {
            relativePath = relativePath.replaceFirst("\\\\", "");
        } else if (relativePath.startsWith("/")) {
            relativePath = relativePath.replaceFirst("/", "");
        }
        String path = "";
        String protocol = Const.class.getClassLoader().getResource("").getProtocol();
        BufferedReader in = null;
        try {
            if (protocol.startsWith("jar")) {
                path = "/static/file-store/" + relativePath;
                InputStream resourceAsStream = FileUtils.class.getClassLoader().getResourceAsStream(path);
                in = new BufferedReader(new InputStreamReader(resourceAsStream, "UTF-8"));

            } else {
                path = System.getProperty("user.dir") + "/src/main/resources/static/file-store/" + relativePath;
                in = new BufferedReader(new FileReader(path));
            }

            String line = "";
            while ((line = in.readLine()) != null) {
                strLine.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return strLine;
    }

    /**
     * 写入TXT文件
     */
    public static void writeTxtFile(String path, String contents) {
        try {
            path = UtilCommon.isLinux() ? path.replaceAll("\\\\", "/") : path.replaceAll("/", "\\\\");
            FileWriter fw = new FileWriter(path);
            fw.write(contents);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 创建完整路径
     *
     * @param path a {@link String} object.
     */
    public static final void mkdirs(final String... path) {
        for (String foo : path) {
            final String realPath = FilenameUtils.normalizeNoEndSeparator(foo, true);
            final File folder = new File(realPath);
            if (!folder.exists() || folder.isFile()) {
                folder.mkdirs();
            }
        }
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName
     * @return
     */
    public static final String getFileExtension(String fileName) {
        int start = fileName.lastIndexOf(".");
        if (start > -1) {
            return fileName.substring(start + 1);
        } else {
            return "";
        }
    }

    /**
     * @Author：
     * @Description：获取某个目录下所有直接下级文件，不包括目录下的子目录的下的文件，所以不用递归获取
     * @Date：
     */
    /**
     * 获取某个目录下所有直接下级文件，不包括目录下的子目录的下的文件，所以不用递归获取
     *
     * @param path    文件绝对路径
     * @param prePath 需要添加的前缀，比如 downloadindex/
     * @Author wyt
     * @Date 2020/12/24
     */
    public static List<String> getFileNames(String path, String prePath) {
        prePath = UtilCommon.getStr(prePath, "");
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        if (file == null || !file.exists()) return null;
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(prePath + "" + tempList[i].getName());
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了，
            }
        }
        return files;
    }

    /**
     * 比特流转文件
     */
    public static File byteToFile(byte[] buf, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {

            file = new File(fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return file;
    }

    /**
     * 删除临时文件
     */
    public static void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        file.delete();
    }

    /**
     * 获取文件后缀名（带点，如 .jpg）
     */
    public static String getFileSuffixWithDot(MultipartFile file) {
        if (file == null || file.getOriginalFilename() == null) {
            return "";
        }
        String originalFilename = file.getOriginalFilename();
        int dotIndex = originalFilename.lastIndexOf(".");
        if (dotIndex == -1 || dotIndex == originalFilename.length() - 1) {
            return "";  // 无后缀或文件名以点结尾（如 test.）
        }
        return originalFilename.substring(dotIndex);
    }

    /**
     * 获取文件后缀名（不带点，如 jpg）
     */
    public static String getFileSuffixWithoutDot(MultipartFile file) {
        String suffixWithDot = getFileSuffixWithDot(file);
        if (suffixWithDot.isEmpty()) {
            return "";
        }
        return suffixWithDot.substring(1);  // 移除点
    }

}
